const { mysql: config } = require('../config')
const { mysql } = require('../qcloud')

module.exports = async (ctx) => {
  const { isbn } = ctx.request.query
  const DB = mysql
    // const DB = require('knex')({
    //   client: 'mysql',
    //   connection: {
    //     host: config.host,
    //     port: config.port,
    //     user: config.user,
    //     password: config.pass,
    //     database: config.db,
    //     charset: config.char,
    //     multipleStatements: true
    //   }
    // })
    const bookDetail = await DB('books')
      .select('books.*', 'cSessionInfo.user_info')
      .join('cSessionInfo', 'books.openid', 'cSessionInfo.open_id')
      .where('isbn', isbn).first()

    const info = JSON.parse(bookDetail.user_info)

    ctx.state.data = Object.assign(bookDetail, {
      tags: bookDetail.tags.split(','),
      summary: bookDetail.summary.split('\n'),
      user_info: {
        name: info.nickName,
        image: info.avatarUrl
      }
    })
		// count 字段+1
		// `update books set count = count + 1 where isbn = ${isbn}`;
		await DB('books').where('isbn', isbn).increment('count', 1)
}
